package com.emath.shared;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.text.format.DateUtils;
import android.util.Log;
import android.widget.Toast;

public class RestClient {
	JSONArray nameArray;
	public JSONArray valArray;
	Context context=null;

	public JSONArray getvalArray() {
		return valArray;

	}
	public RestClient(){
		
	}
	public RestClient(Context thatcontext){
		context=thatcontext;
	}
	
	public int findindex(String y) {
		for (int i = 0; i < nameArray.length(); i++) {
			try {
				if (nameArray.getString(i).equals(y)) {
					return i;

				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return -1;

	}
	public void clear() {
		nameArray = new JSONArray(new ArrayList<String>());
		valArray = new JSONArray(new ArrayList<String>());
	}
	public String convertURL(String str) {

		String url = null;
		try {
			url = new String(str.trim().replace(" ", "%20").replace("&", "%26")
					.replace(",", "%2c").replace("(", "%28")
					.replace(")", "%29").replace("!", "%21")
					.replace("=", "%3D").replace("<", "%3C")
					.replace(">", "%3E").replace("#", "%23")
					.replace("$", "%24").replace("'", "%27")
					.replace("*", "%2A").replace("-", "%2D")
					.replace(".", "%2E").replace("/", "%2F")
					.replace(":", "%3A").replace(";", "%3B")
					.replace("?", "%3F").replace("@", "%40")
					.replace("[", "%5B").replace("\\", "%5C")
					.replace("]", "%5D").replace("_", "%5F")
					.replace("`", "%60").replace("{", "%7B")
					.replace("|", "%7C").replace("}", "%7D"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return url;
	}

	private String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	/*
	 * This is a test function which will connects to a given rest service and
	 * prints it's response to Android Log with labels "Praeda".
	 */
	public void connect(String url) {
		// StrictMode.ThreadPolicy policy = new
		// StrictMode.ThreadPolicy.Builder().permitAll().build();
		// StrictMode.setThreadPolicy(policy);
		HttpParams httpParams = new BasicHttpParams();
		int some_reasonable_timeout = (int) (30 * DateUtils.SECOND_IN_MILLIS);
		HttpConnectionParams.setConnectionTimeout(httpParams, some_reasonable_timeout);
		HttpConnectionParams.setSoTimeout(httpParams, some_reasonable_timeout);
		
		HttpClient httpclient = new DefaultHttpClient(httpParams);

		// Prepare a request object
		HttpGet httpget = new HttpGet(url);
		Log.i("Praeda", url);
		// Execute the request
		HttpResponse response;
		try {
			response = httpclient.execute(httpget);
			// Examine the response status
			Log.i("Praeda", response.getStatusLine().toString());
			

			// Get hold of the response entity
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			// to worry about connection release

			if (entity != null) {

				// A Simple JSON Response Read
				InputStream instream = entity.getContent();
				String result = convertStreamToString(instream);
				Log.i("Praeda", result);

				// A Simple JSONObject Creation
				JSONObject json = new JSONObject(result);
				Log.i("Praeda", "<jsonobject>\n" + json.toString()
						+ "\n</jsonobject>");

				// A Simple JSONObject Parsing
				nameArray = json.names();
				valArray = json.toJSONArray(nameArray);
				for (int i = 0; i < valArray.length(); i++) {
					Log.i("Praeda",
							"<jsonname" + i + ">\n" + nameArray.getString(i)
									+ "\n</jsonname" + i + ">\n" + "<jsonvalue"
									+ i + ">\n" + valArray.getString(i)
									+ "\n</jsonvalue" + i + ">");
				}

				// A Simple JSONObject Value Pushing
				json.put("sample key", "sample value");
				Log.i("Praeda", "<jsonobject>\n" + json.toString()
						+ "\n</jsonobject>");

				// Closing the input stream will trigger connection release
				instream.close();
				httpclient.getConnectionManager().shutdown();

			}

		} catch (ClientProtocolException e) {
			
			// TODO Auto-generated catch block
			Log.e("LOG_TAG", "HTTP Error", e);
			
		} catch (IOException e) {
				Globals.isconnected=0;
				if(context!=null)
					Toast.makeText(context, "Internet Error", Toast.LENGTH_LONG);
					
			// TODO Auto-generated catch block
			  Log.e("LOG_TAG", "Connection Error", e);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}